import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, setToken } from '@/utils/auth'
import { createUniqueString, MD5, aesEcbEncrypt, aesEcbDecrypt, RSAEncrypt } from '@/utils/index'
import validate from '@/utils/validate'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  , timeout: 5000 // request timeout
})

// API数据加密参数
var apiEncryptParams = {};

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }

    // 处理API数据加密
    apiEncryptParams.apiDataEncrypt = validate.validBoolTrue(config.apiDataEncrypt);
    if (apiEncryptParams.apiDataEncrypt) {
      Object.assign(apiEncryptParams, { _k: MD5(createUniqueString()).substring(3, 19) })

      config.data = {
        // 加密AES参数
        reqKey: RSAEncrypt(JSON.stringify(apiEncryptParams), process.env.VUE_APP_RSA_PUBLIC_KEY),
        // 加密API数据
        reqData: aesEcbEncrypt(JSON.stringify(config.data), apiEncryptParams._k)
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 处理自动延期token
    const newToken = response.headers['Authorization']
    if (newToken && newToken !== getToken()) {
      setToken(newToken)
    }

    const res = response.data
    // 处理API加密接口,返回数据的解密
    if (apiEncryptParams.apiDataEncrypt && validate.notEmpty(res.data)) {
      res.data = aesEcbDecrypt(res.data, apiEncryptParams._k)
      res.data = validate.isJson(res.data) ? JSON.parse(res.data) : res.data
    }

    console.log('返回数据：', res)
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== '200') {
      Message({
        message: res.message || 'Error'
        , type: 'error'
        , duration: 5 * 1000
      })

      // 1010004: 登录超时(token验证失败)
      if (res.code === '1010004') {
        // to re-login
        MessageBox.confirm('登录超时, 你可以选择取消停留在当前页面, 或者重新登录', '确认退出', {
          confirmButtonText: '重新登录'
          , cancelButtonText: '取消'
          , type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('错误信息:', error) // for debug
    Message({
      message: error.message
      , type: 'error'
      , duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
